import struct
import random
from threading import Timer
from pymodbus.client import ModbusSerialClient as ModbusClient

class T10(object):
    def __init__(self,port='COM5', baudrate=9600,slave=1,devName='T10'):
        self.port = port
        self.baudrate = baudrate
        self.devName = devName
        self.address = 511
        self.count = 12
        self.slave = slave
    def read_reg(self):
        res = []
        data = []
        client = ModbusClient(port=self.port, baudrate=self.baudrate, name=self.devName)
        client.connect()
        try:
            response = client.read_holding_registers(address=self.address, count=self.count, slave=self.slave)
            res = response.registers
        except Exception as e:
            client.close()
            print(e)
            print('读数据失败，请检查端口是否被占用！')
            return data
        
        data.append(res[0]/10)
        print('湿球温度：%s ℃' % (res[0]/10))
        data.append(res[1]/10)
        print('温度：%s ℃' % (res[1]/10))
        data.append(res[2]/10)
        print('湿度：%s' % (res[2]/10),'%')
        data.append(res[3]/10)
        print('露点温度：%s ℃' % (res[3]/10))
        s = struct.unpack('>f', struct.pack('>2H', res[5], res[4]))
        data.append(s[0])
        print('浮点温度：%f ℃' % (data[4]))
        s = struct.unpack('>f', struct.pack('>2H', res[7], res[6]))
        data.append(s[0])
        print('浮点湿度：%f ℃' % (data[5]))
        s = struct.unpack('>f', struct.pack('>2H', res[9], res[8]))
        data.append(s[0])
        print('浮点露点温度：%f ℃' % (data[6]))
        s = struct.unpack('>f', struct.pack('>2H', res[11], res[10]))
        data.append(s[0])
        print('浮点湿球温度：%f ℃' % (data[7]))
        client.close()
        return data
    def read_random(self):
        data = []
        for i in range(8):
            data.append(random.randint(0, 100))
        return data
    def loop_func(self,func,second):
        func()
        while True:
            timer1 = Timer(second, func)
            timer1.start()
            timer1.join()
#loop_func(read_reg, 1)
if __name__ == '__main__':
    t10 = T10()
    # t10.loop_func(t10.read_reg, 1)
    print(t10.read_reg())
    input()